import React, { useRef, useEffect, useState } from "react";
import { Button, Tooltip, Spin, Slider } from "antd";
import {
  EyeOutlined,
  PauseOutlined,
  PlayCircleOutlined,
  StepBackwardOutlined,
  StepForwardOutlined,
} from "@ant-design/icons";

export interface VideoPosition {
  height: number;
  width: number;
  x: number;
  y: number;
  timestamp?: number; // 完整视频中的绝对时间
}

export interface VideoViewerProps {
  videoUrl: string;
  positions?: VideoPosition[]; // 改回数组形式，支持多个位置
  className?: string;
  style?: React.CSSProperties;
  startTime?: number; // 截取片段的开始时间（完整视频中的绝对时间）
  endTime?: number; // 截取片段的结束时间（完整视频中的绝对时间）
  clipDuration?: number; // 截取片段的实际时长
}

const VideoViewer: React.FC<VideoViewerProps> = ({
  videoUrl,
  positions = [], // 改回数组形式，默认值为空数组
  className = "",
  style = {},
  startTime = 0,
  endTime = 0,
  clipDuration,
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [boxStyles, setBoxStyles] = useState<React.CSSProperties[]>([]);
  const [showMarkers, setShowMarkers] = useState(true);
  const [videoLoaded, setVideoLoaded] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [hasSeeked, setHasSeeked] = useState(false);
  const [currentPositionIndex, setCurrentPositionIndex] = useState<number>(-1);

  // 计算截取片段的实际时长
  const actualClipDuration = clipDuration || endTime - startTime;

  // 将完整视频的绝对时间转换为截取视频中的相对时间
  const convertAbsoluteToRelativeTime = (absoluteTime: number): number => {
    return absoluteTime - startTime;
  };

  // 将截取视频中的相对时间转换为完整视频的绝对时间
  const convertRelativeToAbsoluteTime = (relativeTime: number): number => {
    return relativeTime + startTime;
  };

  // 检查位置时间是否在有效范围内
  const isValidPositionTime = (pos: VideoPosition): boolean => {
    if (!pos || !pos.timestamp) return false;
    const relativeTime = convertAbsoluteToRelativeTime(pos.timestamp);
    return relativeTime >= 0 && relativeTime <= actualClipDuration;
  };

  // 获取有效的所有位置
  const validPositions = positions.filter(isValidPositionTime);

  // 根据当前时间找到应该显示的位置
  const getCurrentPositions = (time: number): VideoPosition[] => {
    return validPositions.filter((pos) => {
      if (!pos.timestamp) return false;
      const relativeTime = convertAbsoluteToRelativeTime(pos.timestamp);
      // 如果时间戳在当前时间的0.5秒内，则显示
      return Math.abs(time - relativeTime) < 0.5;
    });
  };

  // 计算人脸框的相对位置和尺寸
  const calculateBoxStyles = () => {
    const video = videoRef.current;
    if (!video || !video.videoWidth || !video.videoHeight) return;

    const currentPositions = getCurrentPositions(currentTime);
    if (currentPositions.length === 0) {
      setBoxStyles([]);
      return;
    }

    const naturalWidth = video.videoWidth;
    const naturalHeight = video.videoHeight;
    const currentWidth = video.offsetWidth;
    const currentHeight = video.offsetHeight;

    // 计算缩放比例
    const scaleX = currentWidth / naturalWidth;
    const scaleY = currentHeight / naturalHeight;

    const newBoxStyles = currentPositions.map((pos) => ({
      position: "absolute",
      left: `${pos.x * scaleX}px`,
      top: `${pos.y * scaleY}px`,
      width: `${pos.width * scaleX}px`,
      height: `${pos.height * scaleY}px`,
      border: "2px solid #ff4d4f",
      borderRadius: "4px",
      boxSizing: "border-box",
      pointerEvents: "none",
      zIndex: 10,
      boxShadow: "0 0 0 1px rgba(255, 255, 255, 0.3) inset",
    }));

    setBoxStyles(newBoxStyles);
  };

  // 跳转到指定时间（相对时间）
  const seekToTime = (relativeTime: number) => {
    const video = videoRef.current;
    if (video) {
      video.currentTime = relativeTime;
      setCurrentTime(relativeTime);
    }
  };

  // 跳转到第一个人脸出现的时间
  const seekToFirstFace = () => {
    if (validPositions.length > 0) {
      const firstPosition = validPositions[0];
      if (firstPosition.timestamp) {
        const relativeTime = convertAbsoluteToRelativeTime(
          firstPosition.timestamp
        );
        seekToTime(relativeTime);
        setCurrentPositionIndex(0);
      }
    }
  };

  // 跳转到上一个/下一个人脸位置
  const seekToAdjacentFace = (direction: "prev" | "next") => {
    if (validPositions.length === 0) return;

    // 找到当前最近的位置索引
    let newIndex = currentPositionIndex;
    if (newIndex === -1) {
      // 如果没有当前索引，找到第一个时间大于当前时间的位置
      const absoluteCurrentTime = convertRelativeToAbsoluteTime(currentTime);
      newIndex = validPositions.findIndex(
        (pos) => pos.timestamp && pos.timestamp > absoluteCurrentTime
      );
      if (newIndex === -1) newIndex = validPositions.length - 1;
    } else {
      // 根据方向调整索引
      if (direction === "prev") {
        newIndex = Math.max(0, newIndex - 1);
      } else {
        newIndex = Math.min(validPositions.length - 1, newIndex + 1);
      }
    }

    // 跳转到对应位置
    const position = validPositions[newIndex];
    if (position.timestamp) {
      const relativeTime = convertAbsoluteToRelativeTime(position.timestamp);
      seekToTime(relativeTime);
      setCurrentPositionIndex(newIndex);
    }
  };

  // 视频时间更新事件
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      setCurrentTime(video.currentTime);

      // 更新当前位置索引
      const absoluteCurrentTime = convertRelativeToAbsoluteTime(
        video.currentTime
      );
      const newIndex = validPositions.findIndex(
        (pos) =>
          pos.timestamp && Math.abs(pos.timestamp - absoluteCurrentTime) < 0.5
      );
      setCurrentPositionIndex(newIndex);
    };

    video.addEventListener("timeupdate", handleTimeUpdate);
    return () => {
      video.removeEventListener("timeupdate", handleTimeUpdate);
    };
  }, [videoUrl, validPositions]);

  // 视频加载完成后设置初始时间
  useEffect(() => {
    const video = videoRef.current;
    if (video && videoLoaded && !hasSeeked && validPositions.length > 0) {
      const firstPosition = validPositions[0];
      if (firstPosition.timestamp) {
        const relativeTime = convertAbsoluteToRelativeTime(
          firstPosition.timestamp
        );
        // 确保时间在视频范围内
        if (relativeTime >= 0 && relativeTime <= duration) {
          video.currentTime = relativeTime;
          setCurrentTime(relativeTime);
          setCurrentPositionIndex(0);
          setHasSeeked(true);
        }
      }
    }
  }, [videoLoaded, validPositions, hasSeeked, duration]);

  // 视频元数据加载
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleLoadedMetadata = () => {
      setDuration(video.duration);
      setVideoLoaded(true);

      // 视频加载完成后，如果有有效位置，跳转到第一个位置
      if (validPositions.length > 0) {
        const firstPosition = validPositions[0];
        if (firstPosition.timestamp) {
          const relativeTime = convertAbsoluteToRelativeTime(
            firstPosition.timestamp
          );
          if (relativeTime >= 0 && relativeTime <= video.duration) {
            video.currentTime = relativeTime;
            setCurrentTime(relativeTime);
            setCurrentPositionIndex(0);
          }
        }
      }
    };

    video.addEventListener("loadedmetadata", handleLoadedMetadata);
    return () => {
      video.removeEventListener("loadedmetadata", handleLoadedMetadata);
    };
  }, [videoUrl, validPositions]);

  // 视频加载和窗口变化时重新计算
  useEffect(() => {
    calculateBoxStyles();
  }, [currentTime, positions, showMarkers, videoLoaded]);

  useEffect(() => {
    window.addEventListener("resize", calculateBoxStyles);
    return () => {
      window.removeEventListener("resize", calculateBoxStyles);
    };
  }, []);

  const handlePlayPause = () => {
    const video = videoRef.current;
    if (!video) return;

    if (video.paused) {
      video.play();
      setIsPlaying(true);
    } else {
      video.pause();
      setIsPlaying(false);
    }
  };

  const handleSeek = (value: number) => {
    seekToTime(value);
    setCurrentPositionIndex(-1); // 重置位置索引，让组件重新计算
  };

  const toggleMarkers = () => {
    setShowMarkers((prev) => !prev);
  };

  const handleVideoLoad = () => {
    setVideoLoaded(true);
  };

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60);
    const milliseconds = Math.floor((time % 1) * 100);
    return `${minutes}:${seconds.toString().padStart(2, "0")}.${milliseconds
      .toString()
      .padStart(2, "0")}`;
  };

  const formatAbsoluteTime = (time: number) => {
    return formatTime(time);
  };

  const containerStyle: React.CSSProperties = {
    position: "relative",
    display: "inline-block",
    overflow: "hidden",
    border: "1px solid #f0f0f0",
    borderRadius: 8,
    backgroundColor: "#fafafa",
    maxWidth: "100%",
    ...style,
  };

  return (
    <div className={className}>
      <div ref={containerRef} style={containerStyle}>
        {!videoLoaded && (
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              height: 200,
            }}
          >
            <Spin tip="视频加载中..." />
          </div>
        )}
        <video
          ref={videoRef}
          src={videoUrl}
          style={{
            display: "block",
            width: "100%",
            height: "auto",
            visibility: videoLoaded ? "visible" : "hidden",
          }}
          onLoadedMetadata={handleVideoLoad}
          onCanPlay={handleVideoLoad}
          onPlay={() => setIsPlaying(true)}
          onPause={() => setIsPlaying(false)}
          preload="metadata"
        />

        {/* 控制按钮 */}
        <div
          style={{
            position: "absolute",
            bottom: "10px",
            left: "10px",
            right: "10px",
            display: "flex",
            alignItems: "center",
            gap: "8px",
            background: "rgba(0, 0, 0, 0.6)",
            padding: "8px",
            borderRadius: "4px",
            zIndex: 10,
          }}
        >
          <Button
            icon={isPlaying ? <PauseOutlined /> : <PlayCircleOutlined />}
            onClick={handlePlayPause}
            size="small"
            type="primary"
          />
          {validPositions.length > 0 && (
            <>
              <Button
                icon={<StepBackwardOutlined />}
                onClick={() => seekToAdjacentFace("prev")}
                size="small"
                disabled={currentPositionIndex <= 0}
              />
              <Button
                icon={<StepForwardOutlined />}
                onClick={() => seekToAdjacentFace("next")}
                size="small"
                disabled={currentPositionIndex >= validPositions.length - 1}
              />
            </>
          )}
          <span style={{ color: "white", fontSize: "12px", minWidth: "120px" }}>
            {formatTime(currentTime)} / {formatTime(duration)}
            {validPositions.length > 0 &&
              ` (${currentPositionIndex + 1}/${validPositions.length})`}
          </span>
        </div>

        {showMarkers &&
          boxStyles.map((style, index) => <div key={index} style={style} />)}
      </div>

      {/* 时间轴滑块 */}
      {duration > 0 && (
        <div style={{ marginTop: 12 }}>
          <Slider
            min={0}
            max={duration}
            value={currentTime}
            onChange={handleSeek}
            tooltip={{
              formatter: (value) => {
                const absoluteTime = convertRelativeToAbsoluteTime(value || 0);
                return `${formatTime(value || 0)} (绝对: ${formatAbsoluteTime(
                  absoluteTime
                )})`;
              },
            }}
          />
        </div>
      )}

      <div
        style={{
          marginTop: 12,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        {validPositions.length > 0 && (
          <Tooltip title={showMarkers ? "隐藏标记" : "显示标记"}>
            <Button
              icon={<EyeOutlined />}
              size="small"
              type={showMarkers ? "primary" : "default"}
              onClick={toggleMarkers}
            />
          </Tooltip>
        )}
        {videoUrl.substring(videoUrl.lastIndexOf("/") + 1)}
        {/* {validPositions.length > 0 && (
          <span style={{ fontSize: 12, color: '#666' }}>
            检测到 {validPositions.length} 个人脸位置
          </span>
        )} */}
      </div>

      {/* 显示人脸时间点信息 */}
      <div style={{ marginTop: 8, fontSize: 12, color: "#666" }}>
        <div>视频信息:</div>
        <div>
          • 截取时间段: {formatAbsoluteTime(startTime)} -{" "}
          {formatAbsoluteTime(endTime)}
        </div>
        <div>• 截取时长: {formatTime(actualClipDuration)}</div>
        <div>
          • 当前绝对时间:{" "}
          {formatAbsoluteTime(convertRelativeToAbsoluteTime(currentTime))}
        </div>

        {validPositions.length > 0 && (
          <>
            <div style={{ marginTop: 8 }}>人脸出现时间点:</div>
            {validPositions.map((pos, index) => {
              const relativeTime = convertAbsoluteToRelativeTime(
                pos.timestamp || 0
              );
              const isActive = index === currentPositionIndex;
              return (
                <div
                  key={index}
                  style={{
                    padding: "2px 0",
                    color: isActive ? "#1890ff" : "#666",
                    fontWeight: isActive ? "bold" : "normal",
                  }}
                >
                  {index + 1}. {formatTime(relativeTime)} (绝对:{" "}
                  {formatAbsoluteTime(pos.timestamp || 0)}) - 位置: ({pos.x},{" "}
                  {pos.y}), 尺寸: {pos.width}×{pos.height}
                </div>
              );
            })}
          </>
        )}
      </div>
    </div>
  );
};

export default VideoViewer;
